package com.shuai.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shuai.mapper.SysRoleMapper;
import com.shuai.mapper.SysRolePermissionMapper;
import com.shuai.mapper.SysUserRoleMapper;
import com.shuai.model.bo.AllotBo;
import com.shuai.model.converter.SysRoleConverter;
import com.shuai.model.dto.AllotDto;
import com.shuai.model.form.AllotForm;
import com.shuai.model.po.SysRole;
import com.shuai.model.po.SysRolePermission;
import com.shuai.model.po.SysUser;
import com.shuai.model.po.SysUserRole;
import com.shuai.model.query.SysRoleQuery;
import com.shuai.model.vo.SysRoleVo;
import com.shuai.service.SysRoleService;
import com.shuai.utils.converter.PageConverter;
import com.shuai.utils.data.DataUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色信息 服务实现类
 *
 * @author shuai
 * @since 2022
 */
@Slf4j
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    @Resource
    private SysRoleMapper sysRoleMapper;

    @Resource
    private SysUserRoleMapper sysUserRoleMapper;

    @Resource
    private SysRolePermissionMapper sysRolePermissionMapper;

    @Override
    public Integer addSysRole(SysRole sysRole) {
        return sysRoleMapper.insert(sysRole);
    }

    @Override
    public Integer deleteSysRole(SysRoleQuery query) {
        return sysRoleMapper.deleteBatchIds(query.getIds());
    }

    @Override
    public Integer editSysRole(SysRole sysRole) {
        return sysRoleMapper.updateById(sysRole);
    }

    @Override
    public List<SysRoleVo> selectList(SysRoleQuery query) {
        QueryWrapper<SysRole> queryWrapper = new QueryWrapper();
        fillQueryWrapper(queryWrapper, query);
        List<SysRole> roleList = sysRoleMapper.selectList(queryWrapper);
        return SysRoleConverter.convertToVoByPo(roleList);
    }

    @Override
    public IPage<SysRoleVo> selectPage(SysRoleQuery query) {
        QueryWrapper<SysRole> queryWrapper = new QueryWrapper();
        fillQueryWrapper(queryWrapper,query);
        Page<SysRole> page = new Page<>(query.getPage(), query.getLimit());
        IPage<SysRole> pageList = sysRoleMapper.selectPage(page, queryWrapper);
        List<SysRoleVo> records = SysRoleConverter.convertToVoByPo(pageList.getRecords());
        return PageConverter.convertToPage(pageList, records);
    }

    @Override
    public SysRoleVo selectById(Long id) {
        SysRole role = sysRoleMapper.selectById(id);
        return SysRoleConverter.convertToVoByPo(role);
    }

    @Override
    public boolean checkRoleCode(String roleCode) {
        LambdaQueryWrapper<SysRole> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(SysRole::getRoleCode, roleCode);
        SysRole role = sysRoleMapper.selectOne(wrapper);
        return ObjectUtil.isNotEmpty(role) ? false : true;
    }

    @Override
    public AllotBo getUserRoleList(Long userId) {
        //获取所有角色
        List<SysRole> roleList = sysRoleMapper.selectList(new QueryWrapper<SysRole>());
        List<AllotDto> dataVos = SysRoleConverter.convertToAllotDtoByPo(roleList);
        //获取已存在角色Id
        LambdaQueryWrapper<SysUserRole> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(ObjectUtil.isNotEmpty(userId),SysUserRole::getUserId,userId);
        List<String> ids = sysUserRoleMapper.selectList(wrapper).stream()
                .map(SysUserRole::getRoleId).map(String::valueOf).collect(Collectors.toList());
        return AllotBo.builder().allData(dataVos).checkDataId(ids).build();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer allotPermission(AllotForm form) {
        //删除角色权限关系
        LambdaQueryWrapper<SysRolePermission> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(SysRolePermission::getRoleId,form.getRoleId());
        Integer del = sysRolePermissionMapper.delete(wrapper);
        //添加角色权限关系
        Arrays.stream(form.getPermissionIds()).forEach(permissionId->{
            SysRolePermission permission = SysRolePermission.builder().roleId(form.getRoleId())
                    .permissionId(Long.parseLong(permissionId)).build();
            sysRolePermissionMapper.insert(permission);
        });
        return del;
    }


    /**
     * 生成查询条件与排序
     *
     * @param query
     * @return
     */
    private void fillQueryWrapper(QueryWrapper<SysRole> queryWrapper, SysRoleQuery query) {
        //组织查询条件
        queryWrapper.lambda()
                .like(StrUtil.isNotEmpty(query.getRoleNameLike()),SysRole::getRoleName,query.getRoleNameLike())
                .eq(StrUtil.isNotEmpty(query.getRoleTypeEq()),SysRole::getRoleType,query.getRoleTypeEq())
        ;

        //生成order by 的语句
        DataUtil.fillOrderBy(query, queryWrapper, SysUser.class);
    }
}
